package com.wn.class30.tools;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;

import java.io.InputStream;

/**
 * 七牛云工具类
 */
public class QiniuUtil {
    //设置识别用的各种KEY
    private static final String ACCESS_KEY = "CVR1dBd1doiHgTCILQLyOv0n26o-fYpsW8b172hD";
    private static final String SECRET_KEY = "CqvAIk7xGFfFVYoaFXK-ws4vhN35M0DBYoSOZfFE";
    private static final String BUCKET = "hotpotimg";
    private static final String CDN_DOMAIN = "q8rihi6ox.bkt.clouddn.com";
    private static final Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
    /**
     * 图片上传方法
     * @param fileKey 文件名称
     * @param fileStream 文件输入流
     */
    public static void upload(String fileKey, InputStream fileStream) {
        //提供配置信息
        Configuration cfg = new Configuration(Region.region0());
        UploadManager uploadManager = new UploadManager(cfg);

        String upToken = auth.uploadToken(BUCKET);

        Response response = null;
        try {
            //上传
            response = uploadManager.put(fileStream, fileKey, upToken,null,null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            System.out.println(putRet.key);
            System.out.println(putRet.hash);
        } catch (QiniuException e) {
            throw new RuntimeException("上传文件出错",e);
        }
    }



    //生成用于全局访问的网络地址，实际应用时可以直接存入数据库
    public static String fullPath(String fileKey){
        //拼接为数据库图片可以直接访问的路径，例如：http://q8rihi6ox.bkt.clouddn.com/tupian.jpg
        return "http://"+CDN_DOMAIN+"/"+fileKey;
    }

    //删除图片
    public static void deleteImg(String fileKey){
        //提供配置信息
        Configuration cfg = new Configuration(Region.region0());
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        BucketManager bucketMgr = new BucketManager(auth, cfg);
        try {
            Response deleteResponse = bucketMgr.delete(BUCKET, fileKey);
            //捕获图片不存在异常
            if(deleteResponse.statusCode == 612){

            }
        } catch (QiniuException e) {
            e.printStackTrace();
        }

    }
}
